<script setup lang="ts">
import type { FormInstance, InputInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { ExampleGenerate } from './detail'
import { GetDataDetail, PostCreateData, PutModifyData } from '@/api/modules/tuangou'
import detailStore from '@/store/modules/NewCacheData'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<ExampleGenerate>({
  name: '',
  avatar: '',
  levelPic: '',
  labels: '',
  shareTxt: '',
  shareImg: '',
})

const id = route.query.id as string

const rules = reactive({
  name: [
    { required: true, message: '请输入团长名称', trigger: 'blur' },
  ],
  avatar: [
    { required: true, message: '请上传头像', trigger: 'blur' },
  ],
  levelPic: [
    { required: true, message: '请上传等级图片', trigger: 'blur' },
  ],
  shareTxt: [
    { required: true, message: '请输入分享语', trigger: 'blur' },
  ],
  shareImg: [
    { required: true, message: '请上传分享图', trigger: 'blur' },
  ],
})

// 图片上传赋值
function handleUploadSuccess(url: string, key: string) {
  ruleForm.value[key] = url
}

// 标签
const inputValue = ref('')
const inputVisible = ref(false)
const InputRef = ref<InputInstance>()
const dynamicTags = ref<string[]>([])

function handleClose(tag: string) {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}

function showInput() {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

function handleInputConfirm() {
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

// 提交
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      const params = { ...ruleForm.value }
      if (dynamicTags.value.length > 0) {
        params.labels = dynamicTags.value.join(',')
      }
      else {
        ElMessage.error('请添加标签')
        return
      }
      // console.log(params)

      if (id) {
        // 编辑
        params.tuanLeaderId = id

        PutModifyData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('编辑成功')
            router.push({ name: 'tuangouIndex' })
          }
          else {
            ElMessage.error(`编辑失败。${res.errors}`)
          }
        })
      }
      else {
        // 添加
        // console.log(params)

        PostCreateData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('添加成功')
            detailData.emptyFormData('tuanleaderForm')
            router.push({ name: 'tuangouIndex' })
          }
          else {
            ElMessage.error(`添加失败。${res.errors}`)
          }
        })
      }
    }
    else {
      ElMessage.error('请检查表单')
    }
  })
}

onMounted(async () => {
  if (id) {
    await GetDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
        dynamicTags.value = ruleForm.value.labels.split(',')
      }
    })
  }
  else {
    ruleForm.value = detailData.getFormData('tuanleaderForm')
    if (ruleForm.value.labels) {
      dynamicTags.value = ruleForm.value.labels.split(',')
    }
  }

  watch(ruleForm, (newValue) => {
    if (!id) {
      detailData.rememberFormData('tuanleaderForm', newValue)
    }
  }, { deep: true })

  watch(dynamicTags, (newValue) => {
    if (!id) {
      ruleForm.value.labels = newValue.join(',')
    }
  }, { deep: true })
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :rules="rules" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="团长名称" prop="name">
              <el-input v-model="ruleForm.name" placeholder="请输入团长名称" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="16">
            <ElFormItem label="标签">
              <div class="flex gap-2">
                <el-tag
                  v-for="tag in dynamicTags"
                  :key="tag"
                  size="large"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag)"
                >
                  {{ tag }}
                </el-tag>
                <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" class="w-20" @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
                <el-button v-else class="button-new-tag" @click="showInput">
                  创建标签
                </el-button>
              </div>
            </ElFormItem>
          </ElCol>
          <ElCol :md="12">
            <ElFormItem label="分享语" prop="shareTxt">
              <el-input v-model="ruleForm.shareTxt" placeholder="请输入分享语" type="textarea" style="max-width: 550px;" />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="上传图片">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="头像" prop="avatar">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.avatar" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'avatar')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="等级图片" prop="levelPic">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.levelPic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'levelPic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="分享图" prop="shareImg">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.shareImg" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'shareImg')"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>
